package org.jiuling.oss.minio.operation;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.RemoveBucketArgs;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import org.jiuling.oss.minio.exception.MinioRuntimeException;
import org.jiuling.oss.minio.client.factory.MinioFactory;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * Minio存储空间操作
 * @author 紫灵
 * @date 2024年01月08日 20时04分30秒
 */
public class MinioBucketOperation{

    /** Minio客户端 */
    private final MinioClient minioClient;

    public MinioBucketOperation(MinioFactory minioFactory) {
        this.minioClient = minioFactory.buildMinioClient();
    }

    /**
     * 创建一个存储空间
     * @param bucketName 存储空间名称
     */
    public void createBucket(String bucketName){
        try {
            // 判断桶是否存在
            if(!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                 InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException |
                 XmlParserException e) {
            throw new MinioRuntimeException(e);
        }
    }

    /**
     * 获取存储空间名称列表
     * @return 存储空间名称列表
     */
    public List<String> getBucketNameList()  {
        return this.getBucketList().stream().map(Bucket::name).toList();
    }

    /**
     * 获取存储空间列表
     * @return 存储空间列表
     */
    public List<Bucket> getBucketList(){
        try {
            return minioClient.listBuckets();
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                 InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException |
                 XmlParserException e) {
            throw new MinioRuntimeException(e);
        }
    }


    /**
     * 删除存储空间
     * @param bucket 存储空间
     */
    public void deleteBucket(String bucket){
        try {
            // 判断桶是否存在
            if (minioClient.bucketExists(
                    BucketExistsArgs.builder()
                            .bucket(bucket)
                            .build())) {
                minioClient.removeBucket(
                        RemoveBucketArgs.builder()
                                .bucket(bucket)
                                .build()
                );
            }
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                 InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException |
                 XmlParserException e) {
            throw new MinioRuntimeException(e);
        }
    }
}
